# coding=utf-8
import subprocess
import asyncio
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)


def cmd_shell(cmd):
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    out, err = p.communicate(timeout=5)
    return out, err


def task_run():
    with ThreadPoolExecutor() as executor:
        tasks = list()
        all_cmd = ["echo '{}';sleep 2;".format(i) for i in range(5)]
        for info in all_cmd:
            result = executor.submit(cmd_shell, info)
            tasks.append(result)
        for res in tasks:
            print(res.result())


async def sync_task_async_run():
    with ThreadPoolExecutor() as executor:
        tasks = list()
        all_cmd = ["echo '{}';sleep 2;".format(i) for i in range(5)]
        for info in all_cmd:
            result = loop.run_in_executor(executor, cmd_shell, info)
            tasks.append(result)

        results = await asyncio.gather(*tasks)
        for res in results:
            print(res)


def main1():
    task_run()


def main2():
    loop.run_until_complete(sync_task_async_run())
    loop.close()


if __name__ == '__main__':
    t1 = time.time()
    main1()

    print(time.time() - t1)
    t2 = time.time()
    main2()
    print(time.time() - t2)
